package com.qqtop10.manager.utils;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

/**
 * 
 * @ClassName: Jackson
 * @Description: TODO()
 * @author Jovi
 * @date 2015年8月18日 下午4:59:15
 *
 */
public class Jackson {

	public static void main(String[] args) {
		// readJsonObject();
	}

	private static ObjectMapper objectMapper = new ObjectMapper();

	static {
		// 为null的字段不序列号
		objectMapper.setSerializationInclusion(Inclusion.NON_NULL);
	}

	// // 直接写入一个对象
	// public static void writeJsonObject() {
	// ObjectMapper mapper = new ObjectMapper();
	// Location location = new Location(1, "nomouse", 0);
	// try {
	// mapper.writeValue(new File("E:/location.js"), location);
	// } catch (JsonGenerationException e) {
	// e.printStackTrace();
	// } catch (JsonMappingException e) {
	// e.printStackTrace();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
	//
	// // 直接将一个json转化为对象
	// public static void readJsonObject() {
	// ObjectMapper mapper = new ObjectMapper();
	//
	// try {
	// List<Location> location = mapper.readValue(new File("E:/location.js"),
	// new TypeReference<List<Location>>() {
	// });
	// System.out.println(location.size());
	// } catch (JsonParseException e) {
	// e.printStackTrace();
	// } catch (JsonMappingException e) {
	// e.printStackTrace();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }

	// 直接转化为map
	public static void readJsonMap() {
		ObjectMapper mapper = new ObjectMapper();
		try {
			// 需要注意的是这里的Map实际为一个LikedHashMap，即链式哈希表，可以按照读入顺序遍历
			@SuppressWarnings("rawtypes")
			Map map = mapper.readValue(new File("E:/location.js"), Map.class);
			System.out.println(map.get("name") + ":" + map.get("age"));
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将返回结果转Json数据
	 * 
	 * @param result
	 * @param callback
	 * @return
	 */
	public static String result2Json(Map<String, Object> result, String callback) {
		StringBuffer sb = new StringBuffer();
		String json = null;
		try {
			json = objectMapper.writeValueAsString(result);
			if (callback != null && !callback.trim().equals("")) {
				sb.append(callback + "(");
				sb.append(json);
				sb.append(")");
			} else {
				sb.append(json);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	public static String asJson(Object obj) {
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
